<template>
  <div>
   <div class="header">
   <el-card class="box-card">
    <div>曹康</div>
     <!-- 搜索和添加按钮 -->
     <el-form  :inline="true" >
      <div class="style">
         <el-form-item>
        <el-input
        class="input"
        type="text"
        placeholder="根据用户名搜索"
        v-model="input"
        size="small"
        @change="onChange"
        @input="onInput"
        >
        </el-input>
     </el-form-item>
     <el-form-item>
      <el-button size="mini" @click="clear">清空</el-button>
      <el-button size="mini" type="primary" @click="search">搜索</el-button>
    </el-form-item>
      </div>
     <el-form-item type="flex" justify="end">
       <el-button size="mini" class="add" type="success" icon="el-icon-edit"  @click="onAdd">新增权限组</el-button>
     </el-form-item>
    </el-form>
     <!-- 记录条栏 -->
    <div class="tool">
      <i class="el-icon-info" />共{{total}}记录
    </div >
    <!-- 表格 -->
    <el-table
    ref="multipleTable"
    :data="permissionList"
    tooltip-effect="dark"
    style="width: 100%"
    >
    <el-table-column
      type="selection"
      >
    </el-table-column>
    <el-table-column
      prop="title"
      label="用户名"
       align="center"
      >
    </el-table-column>
    <el-table-column
      prop="update_date"
      label="日期"
       align="center"
      sortable
      >
    </el-table-column>
    <el-table-column
      prop="name"
      label="操作"
      align="center"
      >
       <template v-slot='{row}'>
          <el-button size="mini" plain type="primary" icon="el-icon-edit" circle  @click="onEdit(row)"></el-button>
           <el-button size="mini" v-if="row.id!=2" plain type="danger" icon="el-icon-delete" circle @click="onClickDel(row)"></el-button>
       </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
 <el-row type="flex" justify="end" style="height: 50px" align="middle">
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="page.page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="page.pagesize"
      layout="prev,pager,next,sizes,jumper"
      :total="total"
      background
    >
  </el-pagination>
 </el-row>
    </el-card>
   </div>
   <!-- 添加对话框 -->
   <el-dialog
     :title="titleText"
     :visible.sync="dialogVisible"
     width="50%"
     @close="onClose"
   >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="permissionStyle">
      <el-form-item label="用户名" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
     <el-form-item label="权限分配" style="margin-right：12px">
        <el-tree
          :data="treeList"
          show-checkbox
          ref="setPermissionTree"
          node-key="id"
          :default-expanded-keys='[1]'
          highlight-current
          :default-checked-keys="defaultKeys"
          :props="defaultProps">
        </el-tree>
  </el-form-item>
     </el-form>

     <span slot="footer" class="dialog-footer">
       <el-button @click="dialogVisible = false">取 消</el-button>
       <el-button type="primary" @click="onSave">确 定</el-button>
     </span>
</el-dialog>
  </div>
</template>

<script>
import { permissionList, add, remove, update, detail } from '@/api/base/permissions.js'
import { list } from '@/api/base/menus.js'
// const phonejson = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
export default {
  components: {
  },
  data () {
    return {
      input: '',
      page: {
        // total: 0,
        page: 1,
        keyword: '',
        pagesize: 10,
        disabled: 0
      },
      permissionList: [],
      total: 0,
      dialogVisible: false,
      menusList: [],
      treeList: [],
      defaultProps: {
        children: 'childs',
        label: 'title'
      },
      defaultKeys: [],
      form: {
        title: '',
        permissions: this.defaultKeys
      },
      account: '',
      rules: {
        title: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2到 10个字符', trigger: 'blur' }
        ]
        // phone: [
        //   { required: true, message: '请输入手机号', trigger: 'blur', phonejson },
        //   { min: 8, max: 11, message: '长度在 8到 11个字符', trigger: 'blur' }
        // ]
      }
    }
  },
  computed: {
    titleText () {
      return (this.form.id ? '编辑' : '添加') + '权限组'
    }
  },
  created () {
    // 获取权限列表
    this.loadList()
    this.getTreeInfo()
  },
  methods: {
    async  loadList () {
      const res = await permissionList(this.page)
      // 赋值之前对时间进行处理
      res.data.list.forEach(item => {
        item.update_date = this.$dayjs(item.update_date).format('YYYY-MM-DD hh:mm:ss')
      })
      console.log(res.data.list)
      this.total = res.data.counts
      this.permissionList = res.data.list
    },
    handleCurrentChange (newPage) {
      this.page.page = newPage
      this.loadList()
    },
    // 点击搜索
    search () {
      const newArr = this.permissionList.filter(item => { // 一个数组 遍历每个对象
        return item.title.includes(this.input)
      })
      this.permissionList = newArr
      if (newArr.length === 0) {
        this.$message.error('没有该用户名,请重新输入')
        this.loadList()
      }
      if (this.input === '') {
        this.$message.error('输入为空,请重新输入')
      }
    },
    onChange () {
      this.search()
    },
    // 值改变触发
    onInput (val) {
      if (this.input === '') {
        this.loadList()
      }
    },
    // 点击清空
    clear () {
      this.input = ''
      this.loadList()
    },
    // 点击编辑按钮
    async onEdit (row) {
      this.dialogVisible = true
      this.form.id = row.id
      const res = await detail(this.form)
      console.log(res.data)
      this.form = res.data
      // 获取当前角色所拥有的权限
      this.defaultKeys = res.data.permissions
    },
    // 点击添加
    onAdd () {
      this.dialogVisible = true
      // 解决点击添加 重复渲染编辑上的权限点问题
      this.treeList = []
      this.getTreeInfo()
    },
    // 点击了确定
    async onSave () {
      await this.$refs.form.validate(async valid => {
        if (!valid) return
        console.log(this.$refs.setPermissionTree.getCheckedKeys())
        this.form.permissions = [...this.$refs.setPermissionTree.getCheckedKeys()]
        try {
          if (this.form.id) {
          // 编辑
            await update(this.form)
            console.log(123)
            this.$message.success('编辑成功')
          } else {
          // 添加
            this.defaultKeys = []
            await add(this.form)
            console.log(this.defaultKeyss)
            this.$message.success('添加成功')
          }
          this.loadList()
          this.onClose()
        } catch (err) {
          console.log(err)
        }
      })
      this.dialogVisible = false
    },
    // 点击了删除
    onClickDel (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 点击了确定
        await remove(row)
        this.$message.success('删除成功')
        this.loadList()
      }).catch(() => {})
    },
    // 监听对话框关闭
    onClose () {
      setTimeout(() => {
        this.form = {
          title: '',
          permissions: [],
          id: ''
        }
        this.$refs.form.resetFields()
        this.defaultKeys = []
      }, 200)
      this.defaultKeys = []
    },
    async getTreeInfo () {
      // 解决重复渲染
      this.treeList = []
      // 获取菜单列表
      const res = await list()
      this.menusList = res.data
      console.log(res.data)
      this.menusList.map(item => {
        if (item.points && item.points.length) {
          item.childs = item.points
        }
        if (item.childs && item.childs.length) {
          item.childs.forEach(childItem => {
            if (childItem.points && childItem.points.length) {
              childItem.childs = childItem.points
            }
          })
        }
      })
      // 为其添加一个父节点
      const result = {
        id: 1,
        title: '系统菜单和页面权限点',
        childs: [...this.menusList]
      }
      this.treeList.push(result)
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep .el-card {
  .el-form{
    display: flex;
    .style{
      flex: 60%;
    }
  }
  margin: 20px 20px;
  .el-card__body{
    padding: 16px;
  }
  .add{
    // margin-left: 260px;
    align-content: flex-end;
    i{
     color: #fff;
    }

  }
    .tool {
      background-color: #f4f4f5;
      margin: 0;
      height: 30px;
      line-height: 30px;
      font-size: 13px;
       i {
         margin-left: 10px;
      margin-right: 5px;
       font-size: 16px;
      color: #909399;
    }
    }
}
::v-deep .el-dialog__body{
   padding: 30px 20px;
}
.permissionStyle {
      width: 400px;
    margin-left: 120px;
}
::v-deep .el-tree-node__content{
  margin-top: 10px;
}
</style>
